-- UIMagicStone
-- Created by chengb May/21/2015
-- 魔法石柱界面

UIMagicStone = class("UIMagicStone", function()
    return cc.Layer:create();
end);

function UIMagicStone.create(pos)
    return UIMagicStone.new(pos);
end

-- 构造函数
function UIMagicStone:ctor(pos)
    self:setName("UIMagicStone");
    local node = cc.CSLoader:createNode("layout/stone/MagicStone.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录石柱信息
    local gridData = DungeonM.getGridByPos(pos);
    self.gridData = gridData;
    self.stoneId  = self.gridData.id;

    -- 注册点击事件
    self:registerTouchEvent()

    -- 注册事件回调处理函数
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIMagicStone:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIMagicStone:redraw()
    local descLabel  = findChildByName(self.node, "CT/desc");
    local iconImg    = findChildByName(self.node, "CT/icon");
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    local btnOk      = findChildByName(self.node, "CT/btn_ok");
    local kerning, kerning2 = 0, 0;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning, kerning2 = -3, -1;
    end

    local stoneId = self.stoneId;
    local stoneType = MagicStoneM.query(stoneId, "type");
    local dialog    = MagicStoneM.query(stoneId, "dialog");
    local iconName  = MagicStoneM.getStoneIcon(stoneId);
    local iconPath  = getLevelItemIconPath(iconName);
    local title;
    local desc;
    local okBtnText;

    -- 判断石柱是否已关闭
    local isClosed = MagicStoneM.isClosed();
    -- 消耗，需要在已关闭的石柱上动态显示
    local cost = MagicStoneM.calcCost(stoneId);

    if stoneType == STONE_TYPE_LIGHT then
        -- 光之石柱
        title = getLocStr("light_magic_stone_title");
        if isClosed then
            -- 已关闭
            desc = string.format(getLocStr("closed_light_magic_stone_desc"), dialog, table.values(cost)[1])
            okBtnText = getLocStr("btn_text_learn_stone_skill");
        else
            -- 未关闭
            desc = getLocStr("unclose_light_magic_stone_desc");
            okBtnText = getLocStr("btn_text_close_stone");
        end
    else
        -- 暗之石柱
        title = getLocStr("dark_magic_stone_title");
        if isClosed then
            -- 已关闭
            desc = string.format(getLocStr("closed_dark_magic_stone_desc"), dialog, table.values(cost)[1])
            okBtnText = getLocStr("btn_text_learn_stone_skill");
        else
            -- 未关闭
            desc = getLocStr("unclose_dark_magic_stone_desc");
            okBtnText = getLocStr("btn_text_close_stone");
        end
    end


    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    TextStyleM.setArtWordTitleStyle(titleLabel);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, kerning2);

    titleLabel:setString(title);
    iconImg:loadTexture(iconPath);
    btnOk:setTitleText(okBtnText);

    iconImg:setScale(1.2);

    applyString(descLabel, desc);

    -- 显示消耗
    self:redrawCost(cost);
end

-- 重绘消耗
function UIMagicStone:redrawCost(cost)
    local classId = table.keys(cost)[1];
    local needAmount = table.values(cost)[1];
    local curAmount = ItemM.getAmount(ME.user, classId);

    -- 显示材料图标
    local costNode = findChildByName(self.node, "CT/cost_node");
    local iconImg = findChildByName(costNode, "icon");
    local iconPath = getItemIconPath(ItemM.query(classId, "icon"));
    iconImg:loadTexture(iconPath);

    -- 显示数量信息
    local amountLabel = findChildByName(costNode, "amount");

    -- 消耗不足时，显示红色
    if curAmount < needAmount then
        TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
    else
        TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE);
    end
    amountLabel:setString(curAmount .. "/" .. needAmount);
end

-- 注册点击事件
function UIMagicStone:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIMagicStone");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 如果石柱已关闭
            if MagicStoneM.isClosed() then
                -- 判断能否学习技能
                local ret = MagicStoneM.checkStudy();
                if ret ~= true then
                    if ret == "level_upper" then
                        -- 等级已达上限
                        local skillName = MagicStoneM.query(self.stoneId, "name");
                        local msg = string.format(getLocStr("stone_skill_level_upper"), skillName);
                        alert(msg);
                    elseif ret == "item_lack" then
                        -- 材料不足
                        local cost = MagicStoneM.query(self.stoneId, "study_cost");
                        local classId = table.keys(cost)[1];
                        local name = ItemM.query(classId, "name");
                        local msg = string.format(getLocStr("magic_stone_operate_fail"), name);
                        alert(msg);
                    else
                        cclog("学习石柱技能失败。");
                    end
                    return;
                end

                -- 学习技能
                DungeonActionM.go("study_stone");
            else
                -- 判断能否关闭石柱
                local ret = MagicStoneM.checkClosed();
                if ret ~= true then
                    -- 材料不足
                    local cost = MagicStoneM.query(self.stoneId, "closed_cost");
                    local classId = table.keys(cost)[1];
                    local name = ItemM.query(classId, "name");
                    local msg = string.format(getLocStr("magic_stone_operate_fail"), name);
                    alert(msg);
                    return;
                end

                -- 关闭石柱
                DungeonActionM.go("closed_stone", ME.user.dbase:queryTemp("magic_stone", "pos", false));
            end

            -- 限制点击频率
            setClickFrequency(sender, 1);
        end
    end
    btnOk:addTouchEventListener(onOkClick);
end

-- 注册事件回调处理函数
function UIMagicStone:registerEventCallback()
    -- 关注石柱关闭的事件
    EventMgr.register("UIMagicStone", event.CLOSED_STONE, function(args)
        -- 提示玩家
        local stoneId = args.id;
        local stoneType = MagicStoneM.query(stoneId, "type");
        if stoneType == STONE_TYPE_LIGHT then
            alert(getLocStr("close_light_magic_stone_ok"));
        else
            alert(getLocStr("close_dark_magic_stone_ok"));
        end

        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIMagicStone");
    end);

    -- 关注学习石柱技能的事件
    EventMgr.register("UIMagicStone", event.STUDY_STONE, function(args)
        -- 提示玩家
        local stoneId = args.id;

        local effect = MagicStoneM.getEffect(stoneId);

        -- 播放获得新技能的动画
        local skillId = effect["skill_id"];

        -- 播放音效
        AudioM.playFx("scribe_rune");
        self:playGainSkillAnim(skillId, stoneId);
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIMagicStone 界面析构清理");

            EventMgr.removeAll("UIMagicStone");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end
        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 播放获得新技能的动画
function UIMagicStone:playGainSkillAnim(skillId, stoneId)
    local icon = FormulaM.invoke("GET_STONE_SKILL_ICON", skillId);
    local iconPath = getItemIconPath(icon);
    local skillName = SkillM.query(skillId, "name");

    local function playAnim()
        local pos = self.gridData:getPos();
        local grid = UIDungeonMgr.getCurLevel():getAllGrids()[pos];
        pickupSkillEffect(grid, UIDungeonMgr.getCurLevel():getSpellNode(), iconPath, skillName);

        -- 提示学习了新技能
        local dialog = MagicStoneM.query(stoneId, "dialog");
        local msg = string.format(getLocStr("learn_magic_stone_skill_succ"), dialog);
        alert(msg);

        -- 关闭界面
        UIMgr.getCurrentScene():removeFormByName("UIMagicStone");
    end

    performWithDelay(self, playAnim, 0.1);
end









